<template>
  <!-- hidden PageHeaderWrapper title demo -->
  <page-header-wrapper :title="false" class="addmoban">
    <a-row type="flex" justify="space-between" align="top">
      <a-col :span="14">
        <a-card :bordered="false">
          <h3 class="addmoban-title">模板信息</h3>
          <a-spin tip="Loading..." :spinning="spinningFrom">
            <a-form @submit="handleSubmit" :form="form" v-bind="formLayout" class="fzfrom" loadding>
              <a-form-item label="证件模板名称">
                <a-input
                  v-decorator="['template_name', { rules: [{ required: true, message: '请输入证件模板名称！' }] }]"
                  :maxLength="100"
                  placeholder="证件模板名称"
                />
              </a-form-item>

              <a-form-item label="证件标题">
                <a-input
                  v-decorator="['card_name']"
                  :maxLength="100"
                  placeholder="请输入证件标题"
                  @change="cs(1, $event)"
                />
              </a-form-item>
              <a-form-item label="必要字段">
                <span>姓名</span>
              </a-form-item>
              <a-form-item label="属性标题1">
                <a-input
                  v-decorator="['card_key_one', { rules: [{ required: true, message: '请输入属性标题1！' }] }]"
                  :maxLength="100"
                  placeholder="请输入属性标题1"
                  @change="cs(2, $event)"
                />
              </a-form-item>
              <a-form-item label="属性标题2">
                <a-input
                  v-decorator="['card_key_two', { rules: [{ required: true, message: '请输入属性标题2！' }] }]"
                  :maxLength="100"
                  placeholder="请输入属性标题2"
                  @change="cs(3, $event)"
                />
              </a-form-item>
              <a-form-item label="属性标题3">
                <a-input
                  v-decorator="['card_key_three', { rules: [{ required: true, message: '请输入属性标题3！' }] }]"
                  :maxLength="100"
                  placeholder="请输入属性标题3"
                  @change="cs(4, $event)"
                />
              </a-form-item>
              <a-form-item label="持证说明">
                <a-input
                  v-decorator="['card_explain']"
                  :maxLength="100"
                  placeholder="请输入持证说明"
                  type="textarea"
                  @change="cs(5, $event)"
                />
              </a-form-item>
              <a-form-item label="领证有效期">
                <a-date-picker
                  v-decorator="['send_code_ts', { rules: [{ required: true, message: '请选择领证有效截止时间！' }] }]"
                  show-time
                  format="YYYY-MM-DD  HH:mm"
                  placeholder="请选择截止日期"
                  @change="getDate1"
                />
                <span class="yx">在此期间可领用证件</span>
              </a-form-item>
              <a-form-item label="证件有效期" required>
                <a-date-picker
                  v-decorator="['end_ts', { rules: [{ validator: validFunction }], validateTrigger: 'change' }]"
                  show-time
                  format="YYYY-MM-DD  HH:mm"
                  placeholder="请选择截止日期"
                  @change="cs(6, $event)"
                />
                <span class="yx"> 在此期间证件有效</span>
              </a-form-item>

              <a-form-item label="证件照采集">
                <a-checkbox v-model="caiji"> 系统自动采集 </a-checkbox>
                <p class="zjzcj">
                  系统采集领证人认证照片作为证件照，持证人可自行替换。取消勾选则由持证人自行拍摄上传证件照片。
                </p>
              </a-form-item>
              <a-form-item label="电子签章">
                <a-checkbox v-model="qianz"> 出示证件时加盖电子签章 </a-checkbox>
              </a-form-item>

              <a-spin :spinning="spinning">
                <a-form-item :wrapperCol="{ span: 24 }" style="text-align: center">
                  <a-button html-type="submit" type="primary" class="bcbtn">保存</a-button>

                  <a-button @click="handleBack" class="bcbtn">返回</a-button>
                </a-form-item>
              </a-spin>
            </a-form>
          </a-spin>
        </a-card>
      </a-col>
      <!-- 样式一 -->
      <a-col :span="10">
        <certificate-style-one
          :formData="formData"
          :qianz="qianz"
          :imgvalue="imgvalue"
          :isFooter="true"
          :isHead="true"
        />
      </a-col>
    </a-row>
  </page-header-wrapper>
</template>

<script>
import WangEditor from '@/components/Editor/WangEditor.vue'
import { uplaodImg } from '@/api/common.js'
import { addTemplate, getTemplateInfo, getSeal, getCompanyInfo } from '@/api/news'
import ImgUpload from '@/components/upload/ImgUpload.vue'
import { validateURL } from '@/utils/validate.js'
import certificateStyleOne from '@/components/certificateStyle/certificateOne'
import { compareDate, getProtocol } from '@/utils/publicFun'

import moment from 'moment'
import pick from 'lodash.pick'
const fields = [
  'template_name',
  'card_name',
  'card_key_one',
  'card_key_two',
  'card_key_three',
  'card_explain',
  'end_ts',
  'seal',
  'send_code_ts',
]
export default {
  name: 'NewsDetail',
  components: {
    WangEditor,
    ImgUpload,
    certificateStyleOne,
  },
  data() {
    this.formLayout = {
      labelCol: {
        xs: {
          span: 24,
        },
        sm: {
          span: 5,
        },
      },
      wrapperCol: {
        xs: {
          span: 24,
        },
        sm: {
          span: 17,
        },
      },
    }
    return {
      form: this.$form.createForm(this),
      formData: {},
      isClear: false,
      source: '1',
      typeList: [],
      recommendClassList: [],
      uploadkey: Math.random(),
      spinning: false,
      spinningFrom: false,
      id: this.$route.params.id,
      imgvalue: '',
      caiji: true,
      qianz: true,
      template_id2: null,
      tableRef2: '',
      date1: null,
      validFunction: (rule, value, callback) => {
        console.log(value, this.date1)
        if (!value) {
          callback('请选择证件有效截止时间！')
        } else {
          // if (validatePhone(value)) {
          //   this.phone = value
          //   this.isSendSms = true
          //   callback()
          // } else {
          //   this.isSendSms = false
          //   callback('请输入正确的手机号')
          // }
          if (compareDate(value._d || value, this.date1)) {
            callback()
          } else {
            callback('证件有效期截止时间要大于领证有效期')
          }
        }
      },
    }
  },
  props: {
    template_id: {
      type: Number,
    },
    tableRef: {
      type: Object,
    },
  },
  created() {
    console.log(this.$route.query.id)
    if (this.$route.query.id) {
      this.template_id2 = this.$route.query.id
      this.getInfo()
    } else {
      this.form.resetFields()
      this.getcomSeal()
      this.get_company_info()
    }
  },
  watch: {
    template_id: function (v) {
      // 监听传过来的template_id变化，如果改变了去请求接口
      this.template_id2 = v
      console.log(v)
      if (v !== null) {
        this.getInfo()
      } else {
        this.form.resetFields()
        // console.log(this.formData)
        this.formData = {}
        this.get_company_info()
      }
    },
  },
  methods: {
    // 添加或修改模版
    handleSubmit(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          let param = {}
          values.end_ts = moment(values.end_ts).format('YYYY-MM-DD HH:mm:ss')
          values.send_code_ts = moment(values.send_code_ts).format('YYYY-MM-DD HH:mm:ss')
          values.seal = this.qianz ? 1 : 0
          if (this.template_id2) {
            values.template_id = parseInt(this.template_id2)
          }
          this.spinning = true
          addTemplate(values)
            .then((res) => {
              console.log(res)
              if (res.code == 200) {
                this.$message.info(res.msg)
                setTimeout(() => {
                  this.spinning = false
                  this.form.resetFields()
                  this.$router.push({ name: 'NewsTypes' })
                  // this.$router.go(-1)
                }, 1500)
              }
            })
            .catch((err) => {
              console.log(err)
              this.spinning = false
            })
        }
      })
    },
    // 表单返回按钮
    handleBack() {
      this.$router.go(-1)
    },

    // 输入框输入同步两边内容
    cs(sum, event) {
      switch (sum) {
        case 1:
          // this.formData.card_name = event.target.value
          this.formData = Object.assign({}, this.formData, { card_name: event.target.value })

          break
        case 2:
          // this.formData.card_content_one = event.target.value
          // 对象改变页面不更新，es6 assign
          this.formData = Object.assign({}, this.formData, { card_key_one: event.target.value })
          break
        case 3:
          // this.formData.card_content_two = event.target.value
          this.formData = Object.assign({}, this.formData, { card_key_two: event.target.value })

          break
        case 4:
          // this.formData.card_content_three = event.target.value
          this.formData = Object.assign({}, this.formData, { card_key_three: event.target.value })

          break
        case 5:
          // this.formData.card_explain = event.target.value
          this.formData = Object.assign({}, this.formData, { card_explain: event.target.value })

          break
        case 6:
          // this.formData.end_ts = moment(event._d).format('YYYY-MM-DD HH:mm')
          this.formData = Object.assign({}, this.formData, { end_ts: moment(event._d).format('YYYY-MM-DD HH:mm') })

          break
      }
    },
    // 获取详情
    getInfo() {
      this.spinningFrom = true
      this.form.resetFields()

      // company_id先写死, 后期有可能动态
      getTemplateInfo({
        template_id: parseInt(this.template_id2),
        company_id: 0,
      })
        .then((res) => {
          console.log(res)
          // 给表单赋值
          fields.forEach((v) => {
            return this.form.getFieldDecorator(v)
          })
          this.form.setFieldsValue(pick(res.data, fields))
          res.data.seal == 1 ? (this.qianz = true) : (this.qianz = false)
          console.log(res.data)
          if (res.data.company_seal) {
            // this.imgvalue = process.env.VUE_APP_API_BASE_URL2 + res.data.company_seal
            this.imgvalue = getProtocol() + res.data.company_seal
          }
          this.formData = res.data
          this.date1 = res.data.send_code_ts
          this.date2 = res.data.end_ts
          this.spinningFrom = false
        })
        .catch((err) => {
          console.log(err)
        })
    },
    // 获取企业印章
    getcomSeal() {
      getSeal({})
        .then((res) => {
          console.log(res)
          if (res.company_seal) {
            // this.imgvalue = process.env.VUE_APP_API_BASE_URL2 + res.company_seal
            this.imgvalue = window.location.protocol + '//' + window.location.host + res.company_seal
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    // 初始化获取企业单位
    get_company_info() {
      getCompanyInfo({ company_id: '0' })
        .then((res) => {
          console.log(res)
          if (res.data.company_url) {
            this.formData = Object.assign({}, this.formData, { company_url: res.data.company_url })
          }
          this.formData = Object.assign({}, this.formData, { company_name: res.data.company_name })
        })
        .catch((err) => {
          console.log(err)
        })
    },
    // 获取领证日期用于比较证件有效期
    getDate1(value) {
      console.log(value)
      this.date1 = value._d
    },
  },
}
</script>

<style lang="less" scoped>
.addmoban .ant-form-item {
  margin-bottom: 10px;
}

.addmoban-title {
  position: relative;
  font-weight: bold;
  margin-bottom: 30px;
}

.addmoban-title::after {
  position: absolute;
  left: -7px;
  top: 50%;
  margin-top: -6px;
  content: '';
  display: block;
  width: 2px;
  height: 15px;
  background: #1890ff;
}

.yx {
  color: #999;
  font-size: 12px;
  margin-left: 10px;
}

.bcbtn {
  width: 100px;
}

.bcbtn:first-child {
  margin-right: 20px;
}
</style><style lang="less">
.fzfrom .ant-form-item-label > label {
  color: #999999;
}
</style>
